package com.wandian.login.mvvm.userlogin;

import androidx.databinding.DataBindingUtil;

import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bun.miitmdid.core.MdidSdkHelper;
import com.bun.miitmdid.interfaces.IIdentifierListener;
import com.bun.miitmdid.interfaces.IdSupplier;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.MiitHelper;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.DevicesIDUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wandian.login.R;
import com.wandian.login.databinding.LgActivityLoginBinding;

import org.json.JSONException;
import org.json.JSONObject;

import static com.mylib.libcore.config.AppConfig.WX_APP_ID;
import static com.mylib.libcore.config.AppConfig.YLSP_APP_KEY;
import static com.mylib.libcore.config.AppConfig.YLSP_APP_TOKEN;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_OA_ID;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 登录
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_LOGIN)
public class LoginActivity extends  BaseMVVMActivity<LoginActivityViewModel>  {
    private LgActivityLoginBinding dataBinding;
    private boolean openEyes =false;
    private boolean agreementXY = false;
    private IWXAPI api;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.lg_activity_login);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        String oaid = AppContext.getInstance().getAppPreferenceForever().getAppOAID();
        if(UIUtils.isEmpty(oaid))getOAID();
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.registerApp(WX_APP_ID);
        initClink();
        //清除所有缓存activity
        ActivityUtil.getInstance().clearAllActivityWithout(LoginActivity.class);
        if(!UIUtils.isLocationEnabled(this) && UIUtils.isEmpty(AppContext.getInstance().getAppPreferencesHelper().getLocation())){
            ToastUtil.show("为保证功能正常使用，请开启定位服务");
            // 通用版
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String  wx_result =   AppContext.getInstance().getAppPreferencesHelper().getKeyValue("wx_result");
        if(!UIUtils.isEmpty(wx_result)){
            try {
                JSONObject jsonObject = new JSONObject(wx_result);
                if(!UIUtils.isEmpty(jsonObject)){
                    String code = jsonObject.optString("code");
                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("wx_result","");
                    mViewModel.loginByWX(DevicesIDUtil.getDeviceIDAll(LoginActivity.this),code);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    private void initClink(){
        dataBinding.tvAppZc.setOnClickListener(v -> ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_USER_XY).navigation());
        dataBinding.tvAppXy.setOnClickListener(v -> ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_USER_XY).navigation());
        dataBinding.ivLoginEye.setOnClickListener(v -> {
            finishhideSoftBoard();
            openEyes = !openEyes;
            if(openEyes){
                dataBinding.ivLoginEye.setImageResource(R.drawable.login_eye_open);
                dataBinding.etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            }else {
                dataBinding.ivLoginEye.setImageResource(R.drawable.login_eye_close);
                dataBinding.etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        });

        //设备登录
        dataBinding.tvLogin.setOnClickListener(v -> {
            finishhideSoftBoard();
            if(UIUtils.isFastClick()) return;
            if(!agreementXY){
                ToastUtil.show("您还未同意用户协议和隐私政策");
                return;
            }
            String  oaid = AppContext.getInstance().getAppPreferenceForever().getAppOAID();
            if(UIUtils.isEmpty(oaid)){
                mViewModel.loginByDevice(DevicesIDUtil.getDeviceIDAll(LoginActivity.this));
            }else {
                mViewModel.loginByDevice(oaid);
            }

        });

        //微信登录
        dataBinding.ivWx.setOnClickListener(v -> {
            finishhideSoftBoard();
            if(UIUtils.isFastClick()) return;
            if(!agreementXY){
                ToastUtil.show("您还未同意用户协议和隐私政策");
                return;
            }
            if (!api.isWXAppInstalled()) {
                ToastUtil.show("您的设备未安装微信客户端");
            } else {
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                api.sendReq(req);
            }
        });

        dataBinding.ivXy.setOnClickListener(v -> {
            finishhideSoftBoard();
            agreementXY = !agreementXY;
            if(agreementXY)
                dataBinding.ivXy.setImageResource(R.drawable.img_item_choosed);
            else
                dataBinding.ivXy.setImageResource(R.drawable.img_item_unchoose);
        });
    }

    private void getOAID(){
        try {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                MiitHelper miitHelper=  new MiitHelper(new MiitHelper.AppIdsUpdater() {
                    @Override
                    public void OnIdsAvalid(String oaid, String vaid, String aaid) {
                        AppContext.getInstance().getAppPreferenceForever().SetAppOAID(oaid);
                        Log.d("initYLY","oaId="+oaid);
                    }

                    @Override
                    public void getIdError() {
                    }
                });
                miitHelper.getDeviceIds(this);
            }
        }catch (Exception e){

        }

    }


}
